/* global because Sprints.jsp uses this as well */

var sortableFunctions = {
	connectWith: '#content .sortable-list',
	update: function(event, ui) {
	
		// add details of which list and the list itself to the parameters and call servlet
		var parameters = "id=" + this.id
				+ "&list=" + $(this).sortable('toArray').toString();

		$.post("UpdateBacklogPriority", parameters).done(function( data ) {	})
			.fail(function() {
				alert('Error updating backlog priority');
			});
	}
};
		
function getBacklogItemHtml(row) {
	if (row.user_story_story_points === null) row.user_story_story_points = "";
	
	return '<button class="edit-button">Edit</button>\n'
		+ '<button class="delete-button">Delete</button><br>\n'
		+ '<h4>US-' + row.user_story_id + ' ' + row.user_story_name + '</h4>\n'
		+ '<p>'	+ row.user_story_description + '<br>\n'
		+ '<span class="user-story-label">Type: </span>' + row.user_story_type_name
		+ '<span class="user-story-label">Story Points: </span>' + row.user_story_story_points + '</p>\n';
}

function appendDataToBacklog(div_id, row) {
	$("#" + div_id).append(
			'<li id="' + row.user_story_id + '" class="sortable-item">\n'
			+ getBacklogItemHtml(row)
			+ '</li>\n');
	
	$('#content .sortable-list').sortable(sortableFunctions);
}

function updateUserStory(row) {
	$('#' + id).html(getBacklogItemHtml(row));
}

function validateUserStoryData(all_user_story_fields, name, description, user_story_tips) {
	var bValid = true;
	all_user_story_fields.removeClass("ui-state-error");
	bValid = bValid	&& checkLength(name, "name", 1, 50, user_story_tips);
	bValid = bValid	&& checkLength(description,	"description", 1, 250, user_story_tips);
	
	return bValid;
}

function validateTaskData(all_task_fields, name, description, estimate, task_tips) {
	var bValid = true;
	all_task_fields.removeClass("ui-state-error");
	
	bValid = bValid	&& checkLength(name, "task name", 1, 50, task_tips);
	bValid = bValid	&& checkLength(description,	"task description", 1, 250, task_tips);
	bValid = bValid && checkHours(estimate, "Task estimate", 80, task_tips);
	
	return bValid;
}

function validateTestData(all_test_fields, name, description, expected_results, test_tips) {
	var bValid = true;
	all_test_fields.removeClass("ui-state-error");
	
	bValid = bValid	&& checkLength(name, "test name", 1, 50, test_tips);
	bValid = bValid	&& checkLength(description,	"test description", 1, 250, test_tips);
	bValid = bValid && checkLength(expected_results, "test expected results", 1, 250, test_tips);
	
	return bValid;
}

function loadTaskListData() {
	$("div#task-list").html('');
	id = $("#user-story-dialog-form").data('id');
	parameters = "user-story-id=" + id;
	$.getJSON("UserStoryTaskView", parameters).done(function(result) {
		$.each(result.row, function(i, row) {
			appendDataToTaskView(row);
		});
	}).fail(function() {
		alert('Error loading task list');
	});
}

function adjustEmptyTaskFields(row) {
	if (row.task_estimate === 0.0) {
		row.task_estimate = "Not estimated";
	}
	else {
		row.task_estimate = row.task_estimate + ' hours';
	}
	
	if (row.task_assigned_to_name == null) {
		row.task_assigned_to_name = "Not assigned";
	}
}

// tasks view dialog box scripts
function getTaskHtml(row) {
	return '<button class="task-edit-button">Edit</button>\n'
	+ '<button class="task-delete-button">Delete</button>\n'
	+ '<p class="task-header">\n'
	+ '<span class="task-label">ID: </span><span class="task-id">' + row.task_id + '</span>\n'
	+ '<span class="task-label">Name: </span><span class="task-name">' + row.task_name + '</span>\n'
	+ '<span class="task-label">Estimate: </span><span class="task-estimate">' + row.task_estimate + '</span>\n'
	+ '<span class="task-label">Status: </span><span class="task-status">' + row.task_status_name + '</span>\n'
	+ '<span class="task-label">Assigned To: </span><span class="task-assigned-to">' + row.task_assigned_to_name +'</span>\n'
	+ '</p>\n'
	+ '<p class="task-desc">\n'
	+ row.task_description + '\n'
	+ '</p>\n';
}

function appendDataToTaskView(row) {
	adjustEmptyTaskFields(row);
	$("div#task-list").append(
		'<div id="task_' + row.task_id + '" class="task">\n'
		+ getTaskHtml(row)
		+ '</div>\n');
}

function updateTaskForUserStoryData(row) {
	adjustEmptyTaskFields(row);
	$('#task_' + row.task_id).html(getTaskHtml(row));
}

function loadTestListData() {
	// Load JSON data for test list form
	$("div#test-list").html('');
	id = $("#user-story-dialog-form").data('id');
	parameters = "user-story-id=" + id;
	$.getJSON("UserStoryTestView", parameters).done(function(result) {
		$.each(result.row, function(i, row) {
			appendDataToTestView(row);
		});
	}).fail(function() {
		alert('Error loading test list');
	});
}

// tests view dialog box scripts

function getTestCaseHtml(row) {
	return '<button class="test-edit-button">Edit</button>\n'
	+ '<button class="test-delete-button">Delete</button>\n'
	+ '<p class="test-header">\n'
	+ '<span class="test-label">ID: </span><span class="test-id">' + row.id + '</span>\n'
	+ '<span class="test-label">Name: </span><span class="test-name">' + row.name + '</span>\n'
	+ '</p>\n'
	+ '<p class="test-desc">\n'
	+ '<span class="test-label">Description: </span><span class="test-description">' + row.description + '</span>\n'
	+'</p>\n'
	+ '<p class="test-expected-results">\n'
	+ '<span class="test-label">Expected Results: </span><span class="test-expected-results">' + row.expected_results + '</span>\n'
	+'</p>\n';	
}

function appendDataToTestView(row) {
	$("div#test-list").append(
		'<div id="test_' + row.id + '" class="test">\n'
		+ getTestCaseHtml(row)
		+ '</div>\n');
}

function updateTestForUserStoryData(row) {
	$('#test_' + row.id).html(getTestCaseHtml(row));
}

$(function() {
	// add user story dialog box
    var user_story_name = $("#user-story-name" ),
      user_story_description = $("#user-story-description"),
      user_story_story_points = $("#user-story-story-points"),
      all_user_story_fields = $([]).add(user_story_name).add(user_story_description).add(user_story_story_points),
      user_story_tips = $(".userStoryValidateTips"),
      userStoryValidateText = "User Story Name, Description, and Type fields are required.";
    
    $("p.userStoryValidateTips").text(userStoryValidateText);

    // add a task dialog box 
    var task_name = $("#task-name" ),
      task_description = $("#task-description"),
      task_estimate = $("#estimate"),
      task_assigned_to = $("#assigned-to"),
      all_task_fields = $([]).add(task_name).add(task_description).add(task_estimate).add(task_assigned_to),
      task_tips = $(".taskValidateTips"),
      taskValidateText = "Task Name, Description and Status fields are required.";
    
    $("p.taskValidateTips").text(taskValidateText);

    // add a test dialog box 
    var test_name = $("#test-name" ),
      test_description = $("#test-description"),
      test_expected_results = $("#test-expected-results"),
      all_test_fields = $([]).add(test_name).add(test_description).add(test_expected_results),
      test_tips = $(".testValidateTips"),
      testValidateText = "Test Name, Description and Expected Results fields are required.";
    
    $("p.testValidateTips").text(testValidateText);

    // class to force text box to be positive integers
	$(".positive-integer").numeric({ decimal: false, negative: false }, function() {});
	
	// class to force text box to be positive floating point numbers
	$(".positive-float").numeric({ negative: false }, function() {});
	
    // on page load, load the backlog data and display it
	$.getJSON("BacklogView").done(function(result) {
		$.each(result.row, function(i, row) {
			appendDataToBacklog('backlog-list', row);
		});
	}).fail(function() {
		alert('Error loading backlog data');
	});
	
	// set list to be sortable (drag and drop)
	
	$('#content .sortable-list').sortable(sortableFunctions);

	// populate team members dropdown from database
	$.getJSON("GetTeamMembers").done(function(result) {
		$("select[name='assigned-to']").append('<option value="0"> </option>\n');
		$.each(result.row, function(i, row) {
			$("select[name='assigned-to']").append('<option value="' + row.id + '">' + row.name + '</option>\n');
		});
	}).fail(function() {
		alert('Error populating team members dropdown');
	});

	// populate user story types from database
	$.getJSON("GetUserStoryTypes").done(function(result) {
		$.each(result.row, function(i, row) {
			$("select[name='user-story-type']").append('<option value="' + row.id + '">' + row.type_name + '</option>\n');
		});
	}).fail(function() {
		alert('Error populating user story types dropdown');
	});

	// populate task status types from database
	$.getJSON("GetTaskStatusTypes").done(function(result) {
		$.each(result.row, function(i, row) {
			$("select[name='task-status']").append('<option value="' + row.id + '">' + row.name + '</option>\n');
		});
	}).fail(function() {
		alert('Error populating status types dropdown');
	});

	// hide Add new user story button if user is not assigned a project
	if (sessionProjectId == 0) {
		$("#add-user-story").hide();
	}
	
	// add user story dialog box script

	$("#user-story-dialog-form").dialog({
		autoOpen : false,
		height : 500,
		width : 550,
		modal : true
	});

	$("#add-user-story").button().click(function() {
		$("#user-story-dialog-form").dialog('option', 'title', 'Add new user story');
		$("#user-story-dialog-form").dialog({
			buttons : {
				"Add" : function() {
					if (validateUserStoryData(all_user_story_fields, user_story_name, user_story_description, user_story_tips)) {
						$.post("AddUserStoryToBacklog", $("#user-story-form").serialize())
						.done(function( data ) {
							var returnedData = jQuery.parseJSON(data);
							appendDataToBacklog('backlog-list', returnedData);
						}).fail(function() {
							alert('Error adding user story to backlog');
						});
						$(this).dialog("close");
					}
				}
			},
			close : function() {
				closeUserStoryDialogBox(this);
			}
		});
		$("#user-story-dialog-form").dialog("open");

	});
	
	// edit button for user story
	
	$(document).on("click", ".edit-button", function() {
		// get data for dialog box
		
		var user_story_id=$(this).closest('li').attr('id'); // get id from page
		var parameters = "user-story-id=" + user_story_id;

		$.post("GetUserStoryData", parameters).done(function( data ) {
			var returnedData = jQuery.parseJSON(data);
			$("#user-story-dialog-form").data('id', returnedData.user_story_id);
			$('#user-story-name').val(returnedData.user_story_name);
			$('#user-story-description').val(returnedData.user_story_description);
			$('#user-story-type').val(returnedData.user_story_type);
			if (returnedData.user_story_story_points > 0) {
				$('#user-story-story-points').val(returnedData.user_story_story_points);
			}

			$("#user-story-dialog-form").dialog('option', 'title', 'Edit user story US-' + returnedData.user_story_id);
		}).fail(function() {
			alert('Error getting user story data');
		});

		$("#user-story-dialog-form").dialog({
			buttons : {
				"Tests" : function() {
					$("#view-tests-dialog-form").dialog('option', 'title',
							'Tests for US-' + $("#user-story-dialog-form").data('id')
							+ ": " + $('#user-story-name').val());

					$("#view-tests-dialog-form").dialog({
						buttons : {
							"Add a test" : function() {
								$("#test-dialog-form").dialog('option', 'title',
										'New Test for US-' + $("#user-story-dialog-form").data('id')
										+ ": " + $('#user-story-name').val());
								$("#test-dialog-form").dialog({
									buttons : {
										"Add" : function() {
											if (validateTestData(all_test_fields, test_name, test_description, test_expected_results, test_tips)) {
												var user_story_id = $("#user-story-dialog-form").data('id');
												var parameters = "user-story-id=" + user_story_id
														+ "&" + $("#test-form").serialize();

												$.post("AddTestToUserStory", parameters).done(function( data ) {
													var returnedData = jQuery.parseJSON(data);
													loadTestListData();
												}).fail(function() {
													alert('Error adding a test to a user story');
												});
											
												$(this).dialog("close");
											}
										}
									},
									close : function() {
										closeTestCaseDialogBox(this);
									}
								});
								$("#test-dialog-form").dialog('open');							}
						}
					});

					loadTestListData();

					$("#view-tests-dialog-form").dialog('open');
				},
				"Tasks" : function() {
					$("#view-tasks-dialog-form").dialog('option', 'title',
							'Tasks for US-' + $("#user-story-dialog-form").data('id')
							+ ": " + $('#user-story-name').val());
					
					// add buttons to task view dialog box
					$("#view-tasks-dialog-form").dialog({
						buttons : {
							"Add a task" : function() {
								$("#task-dialog-form").dialog('option', 'title',
										'New Task for US-' + $("#user-story-dialog-form").data('id')
										+ ": " + $('#user-story-name').val());
								$("#task-dialog-form").dialog({
									buttons : {
										"Add" : function() {
											if (validateTaskData(all_task_fields, task_name, task_description, task_estimate, task_tips)) {
												var user_story_id = $("#user-story-dialog-form").data('id');
												var parameters = "user-story-id=" + user_story_id
														+ "&" + $("#task-form").serialize();

												$.post("AddTaskToUserStory", parameters).done(function( data ) {
													var returnedData = jQuery.parseJSON(data);
													loadTaskListData();
												}).fail(function() {
													alert('Error adding a task to a user story');
												});
												$(this).dialog("close");
											}
										}
									},
									close : function() {
										closeTaskDialogBox(this);
									}
								});
								$("#task-dialog-form").dialog('open');
							}
						}
					});

					loadTaskListData();
					
					$("#view-tasks-dialog-form").dialog('open');
				},
				"Update" : function() {
					if (validateUserStoryData(all_user_story_fields, user_story_name, user_story_description, user_story_tips)) {
						id = $("#user-story-dialog-form").data('id');
						parameters = "user-story-id=" + id + "&" + $("#user-story-form").serialize();
						$.post("EditUserStory", parameters).done(function(data) {
							var returnedData = jQuery.parseJSON(data);
							updateUserStory(returnedData);
						}).fail(function() {
							alert('Error updating user story');
						});
						
						$(this).dialog("close");
					}
				}
			},
			close : function() {
				closeUserStoryDialogBox(this);
			}
		});
		$("#user-story-dialog-form").dialog("open");

	});
	
	// delete button for user story
	$(document).on("click", ".delete-button", function() {
		var user_story_id = $(this).closest('li').attr('id'); // get id from page
		var user_story_name = $(this).closest('li').children('h4').text();
		var confirmDelete = confirm('Delete ' + user_story_name + ' and any associated tasks and test cases?');

		if (confirmDelete != true) return;
		
		var parameters = "user-story-id=" + user_story_id;

		$.post("DeleteUserStory", parameters).done(function(data) {
			var returnedData = jQuery.parseJSON(data);
			if (returnedData.status == true) {
				$('#' + user_story_id).remove();
			}
		}).fail(function() {
			alert('Error deleting user story');
		});
		
	});

	function closeUserStoryDialogBox(dialogBox) {
		all_user_story_fields.val("").removeClass("ui-state-error");
		all_user_story_fields.val("");
		$("#user-story-type")[0].selectedIndex = 0;
	    $("p.userStoryValidateTips").text(userStoryValidateText);
	    $(dialogBox).dialog("close");
	}
	
	// tasks view dialog box script
	
	// edit a task
	
	$(document).on("click", ".task-edit-button", function() {
		// get data for dialog box
		
		var task_id=$(this).closest('div').attr('id').match(/[\d]+/); // get id from page
		var parameters = "task-id=" + task_id;

		$.post("GetTaskForUserStoryData", parameters).done(function(data) {
			var returnedData = jQuery.parseJSON(data);
			$("#task-dialog-form").data('id', returnedData.task_id);
			$('#task-name').val(returnedData.task_name);
			$('#task-description').val(returnedData.task_description);
			if (returnedData.task_estimate > 0) {
				$('#estimate').val(returnedData.task_estimate);
			}
			$('#task-status').val(returnedData.task_status_id);
			$('#assigned-to').val(returnedData.task_assigned_to_id);

			$("#task-dialog-form").dialog('option', 'title', 'Edit task id ' + returnedData.task_id);
		}).fail(function() {
			alert('Error getting the task data');
		});

		$("#task-dialog-form").dialog({
			buttons : {
				"Update" : function() {
					if (validateTaskData(all_task_fields, task_name, task_description, task_estimate, task_tips)) {
						var parameters = "task-id=" + $("#task-dialog-form").data('id')
								+ '&' + $("#task-form").serialize();

						$.post("EditTaskForUserStory", parameters).done(function(data) {
							var returnedData = jQuery.parseJSON(data);
							updateTaskForUserStoryData(returnedData);
						}).fail(function() {
							alert('Error updating the task');
						});

						$(this).dialog("close");
					}
				}
			},
			close : function() {
				closeTaskDialogBox(this);
			}
		});
		$("#task-dialog-form").dialog("open");
	});

	// delete a task
	$(document).on("click", ".task-delete-button", function() {
		var task_id = $(this).closest('div').attr('id').match(/[\d]+/);
		var task_name = $(this).closest('div').find('.task-name').html();
		
		var confirmDelete = confirm('Delete task ' + task_name + ' (id ' + task_id + ')?');
		if (confirmDelete != true) return;
		
		var parameters = "task-id=" + task_id;
		
		$.post("DeleteTaskFromUserStory", parameters).done(function(data) {
			var returnedData = jQuery.parseJSON(data);
			if (returnedData.status == true) {
				$('#task_' + task_id).remove();
			}
		}).fail(function() {
			alert('Error deleting the task');
		});
	});

	function closeTaskDialogBox(dialogBox) {
		all_task_fields.val("").removeClass("ui-state-error");
		all_task_fields.val("");
		$("#task-status")[0].selectedIndex = 0;
		$("#assigned-to")[0].selectedIndex = 0;
	    $("p.taskValidateTips").text(taskValidateText);
	    $(dialogBox).dialog("close");
	}

	// edit a test case
	
	$(document).on("click", ".test-edit-button", function() {
		// get data for dialog box
		
		var test_id=$(this).closest('div').attr('id').match(/[\d]+/); // get id from page
		var parameters = "test-id=" + test_id;

		$.get("GetTestForUserStoryData", parameters).done(function(data) {
			var returnedData = jQuery.parseJSON(data);
			$("#test-dialog-form").data('id', returnedData.id);
			$('#test-name').val(returnedData.name);
			$('#test-description').val(returnedData.description);
			$('#test-expected-results').val(returnedData.expected_results);

			$("#test-dialog-form").dialog('option', 'title', 'Edit test id ' + returnedData.id);
		}).fail(function() {
			alert('Error getting the test case data');
		});

		$("#test-dialog-form").dialog({
			buttons : {
				"Update" : function() {
					if (validateTestData(all_test_fields, test_name, test_description, test_expected_results, test_tips)) {
						var parameters = "test-id=" + $("#test-dialog-form").data('id')
						+ '&' + $("#test-form").serialize();
						
						$.post("EditTestForUserStory", parameters).done(function(data) {
							var returnedData = jQuery.parseJSON(data);
							updateTestForUserStoryData(returnedData);
						}).fail(function() {
							alert('Error updating the test case');
						});

						$(this).dialog("close");
					}
				}
			},
			close : function() {
				closeTestCaseDialogBox(this);
			}
		});
		$("#test-dialog-form").dialog("open");
	});

	// delete a test case
	
	$(document).on("click", ".test-delete-button", function() {
		var test_id = $(this).closest('div').attr('id').match(/[\d]+/);
		var test_name = $(this).closest('div').find('.test-name').html();
		
		var confirmDelete = confirm('Delete test ' + test_name + ' (id ' + test_id + ')?');
		if (confirmDelete != true) return;
		
		var parameters = "test-id=" + test_id;
		
		$.post("DeleteTestFromUserStory", parameters).done(function(data) {
			var returnedData = jQuery.parseJSON(data);
			if (returnedData.status == true) {
				$('#test_' + test_id).remove();
			}
		}).fail(function() {
			alert('Error deleting the test case');
		});
	});
	
    function closeTestCaseDialogBox(dialogBox) {
		all_test_fields.val("").removeClass("ui-state-error");
		all_test_fields.val("");
	    $("p.testValidateTips").text(testValidateText);
	    $(dialogBox).dialog("close");
    }
    
    // dialog box initial configuration
    
	$("#view-tasks-dialog-form").dialog({
		autoOpen : false,
		height : 600,
		width : 800,
		modal : true
	});

	$("#task-dialog-form").dialog({
		autoOpen : false,
		height : 550,
		width : 550,
		modal : true
	});
	
	$("#view-tests-dialog-form").dialog({
		autoOpen : false,
		height : 600,
		width : 800,
		modal : true
	});

	$("#test-dialog-form").dialog({
		autoOpen : false,
		height : 500,
		width : 550,
		modal : true
	});
});
